<template>
  <el-drawer
    title="查看数据项"
    :visible.sync="drawer"
    :direction="direction"
    :wrapper-closable="false"
    :before-close="handleClose"
    size="50%"
  >
    <div class="drawer-content">
      <div class="dataTitle"><span>数据类：{{materialTypeName}}</span></div>
      <div>
        <dt-table
          ref="table"
          v-loading="loading"
          :is-show-column="false"
          :table-opts="tableOpts"
          :pagination-data="{
            total: total,
            queryParams: filterForm
          }"
          @pagination="pagination"
          @searchReset="handleReset"
          @searchChange="handleQuery"
          @handleSelectionChange="handleSelectionChange"
        >
          <template #toolbarBtn>
            <el-input
              v-model.trim="filterForm.materialName"
              maxlength="30"
              placeholder="请输入枚举项名称"
              style="width:280px"
              clearable
              @keyup.enter.native="handleQuery"
              @clear="handleReset"
            />
            <div class="itemBtnGroup">
              <el-button v-permission="['BASICDATA_ITEM_ADD_BUTTON']" type="primary" @click="openAddDataItem">新建枚举项</el-button>
              <!-- <el-button >导出</el-button>
              <el-button >导入</el-button> -->
              <el-dropdown style="margin-left: 10px;">
                <el-button
                  v-permission="['BASICDATA_ITEM_EXPORT_BUTTON']"
                  :disabled="tableOpts.tableData.length<=0"
                >导出<i class="el-icon-arrow-down el-icon--right" /></el-button>
                <el-dropdown-menu slot="dropdown" style="width:100px;text-align:center">
                  <el-dropdown-item
                    @click.native="handleDownload('all')"
                  >导出所有</el-dropdown-item>
                  <el-dropdown-item
                    @click.native="handleDownload()"
                  >导出选中</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <el-button  style="margin-left: 10px" @click="handleImport" v-permission="['BASICDATA_ITEM_IMPORT_BUTTON']">导入</el-button>
            </div>
          </template>
          <template #enable="enable">
            <el-tag :type="enable.param.enable===1?'success':'info'" >{{enable.param.enable===1?'启用':'禁用'}}</el-tag>
          </template>
        </dt-table>
      </div>
    </div>
    <dataItemEdit ref="dataItemEditRef" @getItemList="getItemList" />
    <dtDialog
      title="枚举项导入"
      :visible.sync="fileUploadVisible"
      width="620px"
      :is-loading="uploadLoading"
      @closeDialog="fileUploadVisible = false"
      @comfirmBtn="importDataSave"
    >
      <el-form slot="content">
        <div class="">
          <dt-importFile ref="dtImportFileRef" :down-load-template="handleImportTemplate" :type="`“${materialTypeName}数据类”枚举项导入`" />
        </div>
      </el-form>
    </dtDialog>
  </el-drawer>

</template>
<script>
import dataItemEdit from './dataItemEdit.vue'
import bussinessUserAuthorizationApi from '@/framework/api/authCenter/bussinessUserAuthorization/bussinessUserAuthorization'
import { basicMaterialPage, basicMaterialDelete, basicMaterialEdit, materialUploadFile, materialDownloadTemplate, exportMaterial, exportAllMaterial } from '@/framework/api/developerCenter/basicData'
import { enable } from '@/framework/api/processDesign/processDesign'
import { dateTimeFormat } from '@/framework/utils/dateTime'

export default {
  dicts: ['roleType'],
  components: { dataItemEdit },
  data() {
    return {
      api: bussinessUserAuthorizationApi,
      drawer: false,
      direction: 'rtl',
      // 遮罩层
      loading: false,
      // 总条数
      total: 0,
      // 用户组织机构关联表格数据
      list: [],
      // 查询参数
      filterForm: {
        materialTypeId: '',
        materialName: '',
        pageNo: 1,
        pageSize: 10
      },
      tableOpts: {
        rowKey: 'id',
        tableData: [],
        toolbarBtn: [],
        customSearch: [{
        }],
        // 表格第一列
        indexTableCol: {
          label: '序号',
          width: 70
        },
        tableCol: [
          {
            prop: 'materialName',
            label: '枚举项名称',
            show: true,
            align: 'left'
          },
          {
            prop: 'materialCode',
            label: '枚举项编码',
            show: true,
            align: 'left'
          },
          {
            prop: 'enable',
            label: '状态',
            show: true,
            align: 'left',
            slotName: 'enable',
            // formatter: () => { return this.dict.type.roleType }
            // 状态 0 禁用 1 启用
            formatter: (row) => { return row.enable === 1 ? '启用' : '禁用' }
          }
        ],
        operator: {
          width: 210,
          align: 'left',
          operatorBtn: [
            {
              text: '禁用',
              permission: ['BASICDATA_ITEM_DISABLED_BUTTON'],
              textChange: (row) => { return row.enable === 1 ? '禁用' : '启用' },
              size: 'mini',
              click: (row, col, cellValue) => {
                return this.handleDisabled(row)
              }
            },
            {
              text: '编辑',
              permission: ['BASICDATA_ITEM_UPDATE_BUTTON'],
              size: 'mini',
              click: (row, col, cellValue) => {
                return this.handleEdit(row)
              }
            },
            {
              text: '删除',
              permission: ['BASICDATA_ITEM_DELETE_BUTTON'],
              size: 'mini',
              type: 'danger',
              click: (row, col, cellValue) => {
                return this.handleDelete(row)
              }
            }
          ]
        }
      },
      userInfo: {},
      id: '',
      materialTypeId: '',
      materialTypeName: '',
      fileUploadVisible: false,
      uploadLoading: false,
      handleImportTemplate: materialDownloadTemplate,
      fileName: `“${this.materialTypeName}数据类”枚举项导入`,
      multipleSelection: []
    }
  },
  watch: {
    'filterForm.materialName': function (n, o) {
      this.getItemList()
    }
  },
  methods: {
    handleOpen(row) {
      this.drawer = true
      this.materialTypeId = row.id
      this.materialTypeName = row.materialTypeName
      this.getItemList()
    },
    handleClose(done) {
      this.filterForm.materialName = ''
      this.$refs['table'].clearSelection()
      done()
    },
    // 新增枚举项
    openAddDataItem() {
      this.$refs.dataItemEditRef.handleData('', 'add', this.materialTypeId)
    },
    // 修改按钮
    handleEdit(row) {
      this.$refs.dataItemEditRef.handleData(row, 'update', this.materialTypeId)
    },
    // 禁用
    handleDisabled(row) {
      const params = {
        id: row.id,
        enable: row.enable === 1 ? 0 : 1
      }
      basicMaterialEdit(params).then(() => {
        this.$dtMessage({
          type: 'success',
          message: row.enable === 1 ? '禁用成功' : '启用成功'
        })
        this.getItemList()
      })
    },
    handleDelete(row) {
      const that = this
      this.$dtModal.confirm(`是否确认移除“${row.materialName}”?`).then(() => {
        return basicMaterialDelete({ ids: [row.id] })
      }).then(() => {
        this.$dtMessage({
          type: 'success',
          message: '删除成功'
        })
        this.getItemList()
      })
    },
    getItemList() {
      this.loading = true
      this.filterForm.materialTypeId = this.materialTypeId
      basicMaterialPage(this.filterForm).then((res) => {
        this.tableOpts.tableData = res.data.rows
        this.total = res.data.totalRows
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.filterForm.pageNo = 1
      this.getItemList()
    },
    /** 重置按钮操作 */
    handleReset() {
      this.filterForm = {
        materialName: '',
        pageNo: 1,
        pageSize: 10
      }
      this.handleQuery()
    },
    pagination() {
      this.getItemList(this.filterForm)
    },
    // 多选框选中数据
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 点击导入
    handleImport() {
      this.fileUploadVisible = true
    },
    // 导入
    importDataSave() {
      const file = this.$refs.dtImportFileRef.fileList
      if (file.length == 0) {
        this.$dtMessage({
          title: '失败',
          message: '请选择需要上传的文件',
          type: 'error',
          duration: 2000
        })
        return
      }
      const formData = new FormData()
      // 数据
      formData.append('file', file[0].raw)
      formData.append('name', file[0].name)
      formData.append('materialTypeId', this.materialTypeId)
      materialUploadFile(formData).then(async (res) => {
        this.uploadLoading = true
        this.fileUploadVisible = false
        if (res.data.errorDownloadPath) {
          this.$alert(`<div> <div class="title">${res.data.tip}</div> <div class="content"><span class="btn" id="messageBtn" style="color:#5688E8;cursor:pointer">点击下载导入失败的信息</span> </div> </div>`, '导入完成', {
            dangerouslyUseHTMLString: true
          })
        } else {
          this.$alert(`<div> <div class="title">${res.data.tip}导入完成`, {
            dangerouslyUseHTMLString: true
          })
        }
        this.getItemList()
        await this.$nextTick()
        document.getElementById('messageBtn').onclick = function () {
          window.location.href = res.data.errorDownloadPath
        }
        this.uploadLoading = false
      }).catch((res) => {
        this.uploadLoading = false
      })
    },
    // 导出
    handleDownload(type) {
      let con = {}
      if (type == 'all') {
        this.showScreenLoading()
        exportAllMaterial({ materialTypeId: this.materialTypeId }).then((res) => {
          const blob = new Blob([res.data], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
          })
          const objectUrl = URL.createObjectURL(blob)
          const a = document.createElement('a')
          a.style.display = 'none'
          a.href = objectUrl // 指定下载链接
          // a.download = '基础数据项' // 指定下载文件名
          const fileType = res.headers['content-disposition'].substring(res.headers['content-disposition'].lastIndexOf('.') + 1).toLowerCase()
          const nowDateTime = dateTimeFormat()
          a.download = `“${this.materialTypeName}数据类”枚举项导出信息${nowDateTime}.${fileType}` // 指定下载文件名
          a.click()
          URL.revokeObjectURL(a.href) // 释放URL对象
          this.hideScreenLoading()
        }).catch((res) => {
          this.hideScreenLoading()
        })
      } else {
        if (!this.multipleSelection || this.multipleSelection.length === 0) {
          this.$dtMessage({
            title: '失败',
            message: '请至少选择一项',
            type: 'error',
            duration: 2000
          })
          return
        }
        const ids = this.multipleSelection.map((res) => {
          return res.id
        })
        con = {
          ids
        }
        this.showScreenLoading()
        exportMaterial(con).then((res) => {
          if (this.tableOpts.tableData == null) {
            this.$dtMessage({
              title: '失败',
              message: res.message,
              type: 'error',
              duration: 2000
            })
          } else {
            const blob = new Blob([res.data], {
              type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            })
            const objectUrl = URL.createObjectURL(blob)
            const a = document.createElement('a')
            a.style.display = 'none'
            a.href = objectUrl // 指定下载链接
            // a.download = '基础数据项' // 指定下载文件名
            const fileType = res.headers['content-disposition'].substring(res.headers['content-disposition'].lastIndexOf('.') + 1).toLowerCase()
            const nowDateTime = dateTimeFormat()
            a.download = `“${this.materialTypeName}数据类”枚举项导出信息${nowDateTime}.${fileType}` // 指定下载文件名
            a.click()
            URL.revokeObjectURL(a.href) // 释放URL对象
            this.hideScreenLoading()
          }
        }).catch((res) => {
          this.hideScreenLoading()
        })
      }
    }
  }
}
</script>
  <style scoped lang="scss">
  .drawer-content{
      padding: 0 24px;
      .dataTitle{
        margin:20px 0;
          height: 24px;
          font-size: 16px;
          font-weight: 400;
          color: #131414;
          line-height: 24px;
      }
      ::v-deep .table-container{
      padding:0;
      box-shadow:none;
  }
  }
  .itemBtnGroup{
    width: 600px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }
  </style>

